/* Copyright 2007 Gearbox Software - http://www.gearboxsoft.com
 
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
 
     http:www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.*/
namespace GearBlog.Web.Utils
{
	using System;
	using System.Collections.Generic;
	using GearBlog.Web.Controllers;
	using GearBlog.Web.Models;
	using GearBlog.Web.Providers;

	public class Notifier
	{
		private INotificationProvider _notificationProvider;
		private ExtendedControllerBase _currentController;
		public ExtendedControllerBase CurrentController
		{
			get { return _currentController;}
		}
		public Notifier(ExtendedControllerBase currentController)
		{
			_currentController = currentController;
			//TODO: To be replaced by IoC container
			_notificationProvider = new EmailNotificationProvider();
			_notificationProvider.SetNotifier(this);
		}

		public void Notify(Post post)
		{
			if (_currentController.Setting.EnableNotifier)
			{
				//retrieve subscription list
				User[] users = RetrievePostSubscriptionUsers(post);
				//dedicate notification to notificationprovider
				try
				{
					_notificationProvider.Notify(post, users);
				}
				catch (Exception exception)
				{
					_currentController.Logger.Error("Exception occurred during post notification (Notify(Post post))", exception);
				}
			}
		}
		public void Notify(Comment comment)
		{
			if (_currentController.Setting.EnableNotifier)
			{
				//retrieve subscription list
				User[] users = RetrievePostSubscriptionUsers(comment);
				//dedicate notification to notificationprovider
				try
				{
					_notificationProvider.Notify(comment, users);
				}
				catch (Exception exception)
				{
					_currentController.Logger.Error("Exception occurred during post notification (Notify(Comment comment))", exception);
				}
			}
		}

		private static User[] RetrievePostSubscriptionUsers(Comment comment)
		{
			List<User> users=new List<User>();
			//Add the poster
			if (!comment.Post.CommentSubscribers.Contains(comment.Post.Author)) users.Add(comment.Post.Author);
			foreach (User user in comment.Post.CommentSubscribers)
			{
				users.Add(user);
			}
			
			return users.ToArray();
		}

		private static User[] RetrievePostSubscriptionUsers(Post post)
		{
			User[] users = User.FindAllByProperty("NotifyNewPost",true);
			return users;
		}
	}
}
